package com.swpu.service_user.controller;



import com.alibaba.fastjson.JSON;
import com.swpu.servicebase.config.BaiduConfig;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
@Scope("prototype")
@ServerEndpoint("/websocket") //暴露的ws应用的路径
public class WebSocketService {

    /**
     * 客户端与服务端连接成功
     * @param session
     */
    static List<Map<String, String>> messages = new ArrayList<>();
    static {
        HashMap<String, String> user = new HashMap<>();

        HashMap<String, String> assistant = new HashMap<>();
        user.put("role", "user");
        user.put("content", "请扮演医生的角色，回答各类健康知识，并向用户提供建议和提醒。请在回答中涵盖健康饮食、适度运动、良好睡眠和心理健康等方面的内容。同时，请提供具体的建议和技巧，如健康饮食的营养搭配、适度运动的运动量控制、良好的睡眠习惯和心理健康的调节方法。请注意，你的回答应该严谨、科学，并具有实际的可操作性。同时，你应该充分尊重用户的健康和隐私，不应泄露任何敏感信息。");
        assistant.put("role", "assistant");
        assistant.put("content","你好");
        messages.add(user);
        messages.add(assistant);
    }
    @Autowired
    private BaiduConfig wenXinConfig;

        /*
            do something for onOpen
            与当前客户端连接成功时
         */
    @OnOpen
    public void onOpen(Session session){
        System.out.println("连接ok");
        session.getAsyncRemote().sendText("数据来了");
    }

    /**
     * 客户端与服务端连接关闭
     * @param session
     */
    @OnClose
    public void onClose(Session session){

        /*
            do something for onClose
            与当前客户端连接关闭时
         */
    }

    /**
     * 客户端与服务端连接异常
     * @param error
     * @param session
     */
    @OnError
    public void onError(Throwable error,Session session) {
    }

    /**
     * 客户端向服务端发送消息
     * @param message

     * @throws IOException
     */
    @OnMessage
    public void onMsg(Session session,String message) {
        OkHttpClient client = new OkHttpClient();
        HashMap<String, String> user = new HashMap<>();
        user.put("role", "user");
        user.put("content", message);
        messages.add(user);
        System.out.println(message);
        System.out.println(messages);
        String requestJson = constructRequestJson(1, 0.95, 0.8, 1.0, true, messages);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestJson);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions" + "?access_token=" + "24.f430d678f178d6745a70c5617c471ef6.2592000.1718034360.282335-58795530")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        StringBuilder answer = new StringBuilder();
        System.out.println("发起请求");
        String temp=null;
        // 发起异步请求
        try {
            Response response = client.newCall(request).execute();
            // 检查响应是否成功
            if (response.isSuccessful()) {
                // 获取响应流
                try (ResponseBody responseBody = response.body()) {
                    if (responseBody != null) {
                        InputStream inputStream = responseBody.byteStream();
                        // 以流的方式处理响应内容，输出到控制台
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {

                            //将结果汇总起来,发送数据
                             temp= new String(buffer, 0, bytesRead);
                            System.out.println(temp.toString());
                            session.getAsyncRemote().sendText(temp.substring(6));
                            answer.append(temp);
                        }
                    }
                }
            } else {
                log.error("流式请求出错"+"Unexpected code " + response);
                System.out.println();
            }
        } catch (IOException e) {
            log.error("流式请求出错");
            throw new RuntimeException(e);
        }
        //将回复的内容添加到消息中
        HashMap<String, String> assistant = new HashMap<>();
        assistant.put("role", "assistant");
        assistant.put("content", "");
        //取出我们需要的内容,也就是result部分
        String[] answerArray = answer.toString().split("data: ");
        for (int i = 1; i < answerArray.length; ++i) {
            answerArray[i] = answerArray[i].substring(0, answerArray[i].length() - 2);
            assistant.put("content", assistant.get("content") + JSON.parseObject(answerArray[i]).get("result"));
        }
        messages.add(assistant);
     //   System.out.println(messages);
       // return assistant.get("content");
    }




    public String constructRequestJson(Integer userId,
                                       Double temperature,
                                       Double topP,
                                       Double penaltyScore,
                                       boolean stream,
                                       List<Map<String, String>> messages) {
        Map<String, Object> request = new HashMap<>();
    //    request.put("user_id", userId.toString());
        request.put("temperature", temperature);
        request.put("top_p", topP);
        request.put("penalty_score", penaltyScore);
        request.put("stream", stream);
        request.put("messages", messages);
        System.out.println(JSON.toJSONString(request));
        return JSON.toJSONString(request);

    }
}


